import os
import random
import shutil
import string
import time
from datetime import datetime, timedelta

from fastapi.requests import Request
from captcha.image import ImageCaptcha

from utils.api_resopnse import api_response
from utils.cache.local_memory import LocalMemoryCache
from utils.helper import generate_uuid, get_session_id
from utils.paths import CaptchaPath


async def generate_captcha(request: Request):
    five_minutes_ago_timestamp = (datetime.now() - timedelta(minutes=5)).timestamp()
    for captcha_path in os.listdir(CaptchaPath):
        this_timestamp = time.mktime(time.strptime(captcha_path, "%Y%m%d%H%M"))
        if this_timestamp < five_minutes_ago_timestamp:
            request.state.logger.info(f"删除过期验证码文件夹: {captcha_path}")
            shutil.rmtree(os.path.join(CaptchaPath, captcha_path))

    # 候选字符集
    charset = string.ascii_lowercase + string.digits
    charset = tuple(set(charset) ^ set("0125losuvz"))  # 排除易混淆字符

    # 随机生成4个字符
    captcha_text = ''.join(random.sample(charset, 4))

    # 保存到session中
    cache = LocalMemoryCache()
    cache.set(get_session_id(request) + "_captcha", captcha_text.upper(), 60 * 2)  # 验证码有效期2分钟

    request.session["captcha"] = captcha_text.upper()

    # 生成验证码图片
    current_day = datetime.now().strftime("%Y%m%d%H%M")
    image_name = f"{generate_uuid()}.png"
    image_dir = os.path.join(CaptchaPath, current_day)
    image_path = os.path.join(image_dir, image_name)

    if not os.path.exists(image_dir):
        os.makedirs(image_dir)

    image = ImageCaptcha().generate_image(captcha_text.upper())
    image.save(image_path)

    return api_response(data={"captcha": request.url_for("temp", path=f"images/captcha/{current_day}/{image_name}").path})
